import base64
from pydantic import Field
import requests

from odoo import exceptions
from ..shippypro import api_key, headers, shippypro_url
import json
import logging
from odoo import _, api, models
from odoo.modules.registry import Registry
from odoo.tools.config import config

_logger = logging.getLogger(__name__)

key = api_key
headers = headers
url = shippypro_url


class BaseAPI(object):

    # key = ""
    # APIOrdersID = ""
    # @classmethod
    # def __init__(self):
    #     reg = Registry(config.get("db_name"))
    #     cursor = reg.cursor()
    #     env = api.Environment(cursor, 1, context={})
    #     icp = env['ir.config_parameter'].sudo()
    #     key = icp.get_param('shippypro_key')
    #     APIOrdersID = icp.get_param('shippypro_orderid')

    @staticmethod
    def get_config(key):
        reg = Registry(config.get("db_name"))
        cursor = reg.cursor()
        env = api.Environment(cursor, 1, context={})
        icp = env["ir.config_parameter"].sudo()
        return icp.get_param(key)
        # APIOrdersID = icp.get_param("shippypro_orderid")
        # return {"key": key, "APIOrdersID": APIOrdersID}

    @classmethod
    def post(cls, method, params={}, custom_headers={}):
        # with api.Environment.manage() as manager:
        # reg = Registry(config.get("db_name"))
        # cursor = reg.cursor()
        # env = api.Environment(cursor, 1, context={})
        # icp = env["ir.config_parameter"].sudo()
        key = cls.get_config("shippypro_key")
        # APIOrdersID = icp.get_param("shippypro_orderid")
        key = key + ":"
        # key = b'I like Python'
        token = base64.b64encode(key.encode())
        token = token.decode()
        values = {"Method": method, "Params": params}
        data = json.dumps(values)
        _logger.info("%s post请求: %s", __name__, data)
        response = requests.post(
            url,
            data=data,
            headers={
                **{
                    "Content-Type": "application/json",
                    # 'Authorization': 'Basic NjQ2OWMzNjc0YzE3NGRiYmQxNGI5NGFkMDMxYTIzZDY6'
                    "Authorization": "Basic " + token,
                },
                **custom_headers,
            },
        )
        _logger.info("%s post请求结果: %s", __name__, response.text)
        response_dict = json.loads(response.text)
        # print(response_dict)
        if "Error" in response_dict:
            raise exceptions.UserError(
                _("调用接口失败，失败原因：%s", response_dict["Error"])
            )
        return response_dict
